package com.vehicle.common.util.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by yantingbin on 2017/7/29.
 */
public class NamedPoolThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNum=new AtomicInteger(1);

    private final AtomicInteger threadNum=new AtomicInteger(1);

    private final ThreadGroup group;
    private final String namePre;
    private final Boolean isDaemon;

    public NamedPoolThreadFactory(String prefix){
        this(prefix,false);
    }

    public NamedPoolThreadFactory(String prefix, boolean daemon){
        SecurityManager manager=System.getSecurityManager();
        if(manager!=null){
             group=manager.getThreadGroup();
        }else{
            group=Thread.currentThread().getThreadGroup();
        }
        isDaemon=daemon;
        namePre=prefix+"-p-"+poolNum.getAndIncrement()+"-t-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t=new Thread(group,r,namePre+threadNum.getAndIncrement(),0);
        t.setContextClassLoader(NamedPoolThreadFactory.class.getClassLoader());
        t.setPriority(Thread.NORM_PRIORITY);
        t.setDaemon(isDaemon);
        return t;
    }
}
